package com.example.ecommercemarketing.config;

import com.alibaba.ttl.threadpool.TtlExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

/**
 * 营销系统线程池配置
 */
@Configuration
public class ThreadPoolConfig {
    private static final Object PRODUCT_CENTER_THREAD_POOL_LOCK = new Object();
    /**
     * 产品中心通用线程池
     */
    private volatile static ThreadPoolExecutor productCenterThreadPool;

    /**
     * 使用Ttl包装的“产品中心通用线程池”
     *
     * @return ExecutorService
     */
    @Bean("productCenterThreadPoolTtl")
    public static ExecutorService getProductCenterThreadPoolTtl() {
        //return TtlExecutors.getTtlExecutor(getProductCenterThreadPool());
        return TtlExecutors.getTtlExecutorService(getProductCenterThreadPool());
    }

    /**
     * 获取“产品中心通用线程池”
     */
    public static ThreadPoolExecutor getProductCenterThreadPool() {
        if (productCenterThreadPool == null) {
            synchronized (PRODUCT_CENTER_THREAD_POOL_LOCK) {
                if (productCenterThreadPool == null) {
                    // 创建线程工厂
                    ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("ProductCenter_ThreadPool-%d").build();
                    //创建线程池
                    //常驻线程数
                    int threadCnt = 32;
                    //最大线程数
                    int threadMax = 128;
                    //临时线程存活时间
                    long keepAliveTime = 60L;
                    productCenterThreadPool = new ThreadPoolExecutor(
                            threadCnt,
                            threadMax,
                            keepAliveTime,
                            TimeUnit.SECONDS,
                            new ArrayBlockingQueue<>(256),
                            threadFactory,
                            new ThreadPoolExecutor.CallerRunsPolicy()
                    );
                }
            }
        }

        return productCenterThreadPool;
    }

    /**
     * 营销素材获取专用线程池
     */
    @Bean("marketingThreadPool")
    public ThreadPoolExecutor marketingThreadPool() {
        int corePoolSize = Runtime.getRuntime().availableProcessors();
        int maxPoolSize = corePoolSize * 2;

        return new ThreadPoolExecutor(
                corePoolSize,                      // 核心线程数 = CPU核心数
                maxPoolSize,                       // 最大线程数 = CPU核心数 * 2
                60L,                               // 空闲线程存活时间(秒)
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1000),   // 有界队列（防止OOM）
                new NamedThreadFactory("marketing-pool"), // 自定义线程工厂
                new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略：由调用线程执行任务
        );
    }
}